<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Cas\Cas;
use App\Cas\CasService;
use App\Models\Access\User\User;

class AccessController extends Controller
{

    private function redirectPath()
    {
        return route('welcome');
    }

    public function casLogin(Request $request)
    {
        $ticket = $request->input("ticket");
        \Log::info("cas ticket: $ticket");
        if (empty($ticket)) {
            return redirect(Cas::casLoginUrl());
        } else {
            $rs = CasService::casValidate($ticket, Cas::getServiceUrl());
            if ($rs->getSuccess()) {
                $user_name = $rs->getUser();
                \Log::info("login user: $user_name");
                //user_name唯一
                $user = User::where('name', $user_name)->withTrashed()->first();
                if (empty($user)) {
                    $attrs = $rs->getAttributes();

                    $user = new User();
                    $user->name = $user_name;
                    if (empty($attrs->cnName)) {
                        $user->real_name = $user_name;
                    } else {
                        $user->real_name = $attrs->cnName;
                    }
                    $user->email = empty($attrs->email) ? '':encrypt_func($attrs->email,$user_name);
                    $user->phone = empty($attrs->mobile) ? '':encrypt_func($attrs->mobile,$user_name);
                    $user->status = 0;
                    $user->save();
                }
                //role_id=1是超级管理员组
                $roleId = isset($user->roles[0]) ? $user->roles[0]['id'] : 0;
                //禁用用户退出登陆
                if ($user->status === 0) {
                    if(!empty($user->deleted_at)) {
                        \Auth::logout();
                        abort(500, '您已被禁用，请联系管理员！');
                    } elseif($user->id != User::SUPER_ADMIN) {
                        abort(501, '您目前还没有权限，请联系管理员！');
                    }
                }

                //用user id登录
                \Auth::loginUsingId($user->id);
                return redirect()->intended(route("admin.index"));
            }
        }
        return redirect(Cas::casLoginUrl());
    }

    public function logout(Request $request)
    {
        \Auth::logout();
        return view('backend.logout');
    }
}